package com.way.fileexplorer.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;

public class ImageLoader {

	private Object lock = new Object();

	private boolean mAllowLoad = true;

	private boolean firstLoad = true;

	private int mStartLoadLimit = 0;

	private int mStopLoadLimit = 0;

	private boolean mDone = false; // bug 211092

	final Handler handler = new Handler();

	private Context mContext;

	public ImageLoader(Context context) {
		mContext = context;
	}

	public interface OnImageLoadListener {
		public void onImageLoad(int position, Bitmap drawable);
		// public void onError(Integer t);
	}

	public void setLoadLimit(int startLoadLimit, int stopLoadLimit) {
		if (startLoadLimit > stopLoadLimit) {
			return;
		}
		mStartLoadLimit = startLoadLimit;
		mStopLoadLimit = stopLoadLimit;
	}

	public void restore() {
		mAllowLoad = true;
		firstLoad = true;
	}

	public void lock() {
		mAllowLoad = false;
		firstLoad = false;
	}

	public void unlock() {
		mAllowLoad = true;
		synchronized (lock) {
			lock.notifyAll();
		}
	}

	public void loadImage(Integer t, String imageUrl,
			OnImageLoadListener listener, final boolean isImage) {
		final OnImageLoadListener mListener = listener;
		final String mImageUrl = imageUrl;
		final Integer mt = t;

		new Thread(new Runnable() {

			@Override
			public void run() {
				if (!mAllowLoad) {
					synchronized (lock) {
						try {
							lock.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}

				if (mAllowLoad && firstLoad) {
					loadImage(mImageUrl, mt, mListener, isImage);
				}

				if (mAllowLoad && mt <= mStopLoadLimit && mt >= mStartLoadLimit) {
					loadImage(mImageUrl, mt, mListener, isImage);
				}
			}

		}).start();
	}

	private void loadImage(final String mImageUrl, final Integer mt,
			final OnImageLoadListener mListener, boolean isImage) {

		// bug 211092 begin
		if (mDone) {
			return;
		}

		final Bitmap map = FileUtil.readBitMap(mImageUrl, isImage, mContext);
		handler.post(new Runnable() {
			@Override
			public void run() {
				if (mDone) {
					return;
				}
				// bug 211092 end
				if (mAllowLoad && map != null) {
					mListener.onImageLoad(mt, map);
				}
			}
		});
	}

	// 211092 begin
	public void stop() {
		mDone = true;
	}
	// 211092 end

}
